import * as THREE from 'three'
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js'
import {EffectComposer} from 'three/examples/jsm/postprocessing/EffectComposer.js'
import {DotScreenPass} from 'three/examples/jsm/postprocessing/DotScreenPass.js'
import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js'
import { GlitchPass } from 'three/examples/jsm/postprocessing/GlitchPass.js'
import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js'
import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js'

import {GUI} from 'lil-gui'

const gui = new GUI()

const scene = new THREE.Scene()

const gltfLoader = new GLTFLoader()
const cubeLoader = new THREE.CubeTextureLoader()

const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight)
camera.position.set(2,2,2)
scene.add(camera)

const renderer = new THREE.WebGLRenderer()
renderer.shadowMap.enabled = true
renderer.shadowMap.type = THREE.PCFSoftShadowMap
renderer.outputColorSpace = THREE.SRGBColorSpace
renderer.toneMapping = THREE.ACESFilmicToneMapping
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))

const envMap = cubeLoader.setPath('/env/').load(['px.jpg', 'nx.jpg', 'py.jpg', 'ny.jpg', 'pz.jpg', 'nz.jpg'])
envMap.colorSpace = THREE.SRGBColorSpace

scene.background = envMap
scene.environment = envMap

const updateMaterials = () => {
  scene.traverse(item => {
    if(item instanceof THREE.Mesh && item.material instanceof THREE.MeshStandardMaterial) {
      item.material.envMapIntensity = 2.5
      item.material.needsUpdate = true
      item.castShadow = true
      item.receiveShadow = true
    }
  })
}

gltfLoader.load('/model/index.gltf', (gltf) => {
  scene.add(gltf.scene)
  updateMaterials()
})

const composer = new EffectComposer(renderer)
// composer.setPixelRatio(window.devicePixelRatio)
// composer.setSize(window.innerWidth, window.innerHeight) // 可以不写 内部已经实现了

composer.addPass(new RenderPass(scene, camera))

const dotPass = new DotScreenPass()
dotPass.enabled = false

composer.addPass(dotPass)

const glitch = new GlitchPass()
glitch.enabled = false
composer.addPass(glitch)

const boom = new UnrealBloomPass(new THREE.Vector2(), 0.3, 1, 0.6)
composer.addPass(boom)

gui.add(boom, 'strength').min(0).max(10).step(0.1)
gui.add(boom, 'radius').min(0).max(10).step(0.1)

document.body.appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true

const light = new THREE.AmbientLight('#ffffff', 2)
scene.add(light)


window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()

  renderer.setSize(window.innerWidth, window.innerHeight)
  renderer.setPixelRatio(window.devicePixelRatio)
})

const tick = () => {
  controls.update()
  composer.render()
  window.requestAnimationFrame(tick)
}

tick()
